<template>
  <el-upload
  class="avatar-uploader"
  action="https://jsonplaceholder.typicode.com/posts/"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload"
  :http-request='upload'
  
  >
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</template>

<script>
// 导入 cos 模块
const COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
 SecretId: 'AKIDDJFYpupy59CWdZOTbYO3YpvqpdP9mHkD',
SecretKey: 'fIQSoS4gBZtDa8mSC3eRDwb9j9RZdYKv'
})
  export default {
    data() {
      return {
        imageUrl: ''
      };
    },
    methods: {
      handleAvatarSuccess(res, file) {
        //res 是后端返回的相应数据
        // file 前端上传的文件对象的信息，本地磁盘里的文件
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type =='image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
       // 自定义上传属性
  upload(res) {
    if (res.file) {
      cos.putObject({
        Bucket: 'chenjiawei-1304781796', // 存储桶的名称，必须
        Region: 'ap-nanjing', // 存储桶所在地域，必须字段
        Key: res.file.name, // 文件名，必须
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: res.file, // 上传文件对象
        // 上传进度条
        onProgress: function(progressData) {
          // console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        this.imageUrl = `https:${data.Location}`
          //  console.log(err||data);
      })
    }
  }
}
    }
  
</script>

<style scoped >
 .avatar-uploader .el-upload {
   
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
